//
//  ManagementeGroupVC.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/5/3.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "ManagementeGroupVC.h"
#import "SYNewAlerView.h"


#define CellSP 25*fw
#define CellW 35*fw
@interface ManagementeGroupVC ()<ZXFDCCVNavSelectedDelegate>
{
    int merginIndex;//要合并的对象
    int haveSelectedIndex;
}
@property (nonatomic, strong) UIButton *addBtn;//添加按钮

@property (nonatomic, strong) NSMutableArray *dataListArr;

@property (nonatomic, strong) SYNewAlerView *alerView;

@property (nonatomic, strong) SYWenTiFenZuModel *sortModel;//新
@property (nonatomic, strong) SYWenTiFenZuModel *oldSortId;//旧


@end

@implementation ManagementeGroupVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _dataListArr = [NSMutableArray array];
    
}
- (void)initSubView{
    merginIndex = -1;
    haveSelectedIndex=-1;
    
    [self.view addSubview:self.mainCollectionViewController];
    [_mainCollectionViewController mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@44);
        make.bottom.equalTo(@0);
    }];
    [self.view addSubview:self.navView];
    [_navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@0);
        make.height.equalTo(@44);
    }];
    [self.navView addSubview:self.addBtn];
    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.navView.mas_right).offset(-20);
        make.centerY.equalTo(self.navView.mas_centerY);
        make.width.height.mas_equalTo(40);
    }];
    [self requestDataListArr];
}
- (MGNavView *)navView{
    if (!_navView) {
        MGNavView *view = [[MGNavView alloc]init];
        view.backgroundColor = MAINBACKCOLOR;
        view.delegate = self;
        view.titleLabe.text = @"管理分组";
        _navView = view;
    }
    return _navView;
}
- (void)backClick{
    [UIView animateWithDuration:0.5 animations:^{
        self.view.frame = CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height);
    }completion:^(BOOL finished) {
        if (self.block) {
            self.block(@"11");
        }
        [self.view removeFromSuperview];
    }];
}
- (void)submiteClick{
    
}
- (UICollectionView *)mainCollectionViewController {
    if (!_mainCollectionViewController) {
        //自动网格布局
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _mainCollectionViewController = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, APP_HEIGHT-84) collectionViewLayout:flowLayout];
        _mainCollectionViewController.delegate = self;
        _mainCollectionViewController.dataSource = self;
        _mainCollectionViewController.backgroundColor = [UIColor whiteColor];
        [_mainCollectionViewController registerClass:[MGCollectionViewCell class] forCellWithReuseIdentifier:@"MGCollectionViewCell"];
        [_mainCollectionViewController registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"view"];
        [_mainCollectionViewController registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"view"];
    }
    return _mainCollectionViewController;
}
#pragma mark == collectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(200, 140);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (_Type == YES) {
        return UIEdgeInsetsMake(CellSP, CellSP, CellSP,CellSP);
    }else{
        return UIEdgeInsetsMake(CellSP, CellW, CellSP,CellW);
    }
    
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(_mainw,0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(_mainw, 0);
}
//设置分区数（必须实现）
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//设置每个分区的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataListArr.count;
}
//设置返回每个item的属性必须实现）
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SYWenTiFenZuModel *wtfz = self.dataListArr[indexPath.row];
    MGCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MGCollectionViewCell" forIndexPath:indexPath];
    cell.indexPath = (int)indexPath.row;
    
    cell.nameLabel.text = wtfz.sortName;
    cell.countLabel.attributedText = [PublickFunctionObject getPriceAttribute:SYStringWithPickFormat(@"数量：", wtfz.sortNums) and:[UIColor redColor] andChangeBenginString:@"：" andEndString:@"" andSize:13];;
    
    cell.deleteBlock = ^(int index) {
        //删除
        [self deletAlertDeleteId:wtfz.sortId];
    };
    __weak typeof(self) weakSelf = self;
    cell.resetNameBlock = ^(int index) {
        weakSelf.alerView = [[SYNewAlerView alloc] init];
        [weakSelf.alerView showAler:weakSelf.alerView titleName:@"重命名" textFielPlo:@" 填写新名字"];
        
        weakSelf.alerView.block = ^(NSString *titleName) {//先这样写着。到时候在更改
            [weakSelf reuqestdataName:titleName fzId:wtfz.sortId];
        };
    };
    
    cell.merginBlock = ^(int index) {
        //合并
        if (self->haveSelectedIndex < 0) {
            self->merginIndex = index;
            self->haveSelectedIndex = index;
            weakSelf.oldSortId = wtfz;
        }else{
            self->haveSelectedIndex = -1;
            self->merginIndex = -1;
            //没有选择合并目标，删除b选中状态
        }
         [self->_mainCollectionViewController reloadData];
    };
     //重新选择了合并对象时每次都重置状态
    [cell resetSelectedObject];
    cell.selectedBlock = ^(int index) {
        weakSelf.sortModel = wtfz;
        //选中的合并对象
        [self merginAlert:index];
    };
    if (merginIndex >= 0) {
        if (merginIndex == (int)indexPath.row) {
            cell.selectedButton.hidden = YES;
        }else{
            cell.selectedButton.hidden = NO;
        }
    }else{
        cell.selectedButton.hidden = YES;
    }
    return cell;
}
- (void)merginAlert:(int)index{
    NSString *titleName = [NSString stringWithFormat:@"是否将%@合并到%@ ？",self.oldSortId.sortName,self.sortModel.sortName];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:titleName preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self->_mainCollectionViewController reloadData];
    }];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self->haveSelectedIndex = index;
        [self yidongwenjianjiaOldId:self.oldSortId.sortId newId:self.sortModel.sortId];
    }];
    [alert addAction:cencel];
    [alert addAction:confirm];
    alert.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)deletAlertDeleteId:(NSString *)delid {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"删除后该分组下的问题将变为无分组状态,是否继续?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestDeleteId:delid];
    }];
    [alert addAction:cencel];
    [alert addAction:confirm];
    alert.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:alert animated:YES completion:nil];
}
//对头视图或者尾视图进行设置
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"view" forIndexPath:indexPath];
        return view;
}
//是否允许移动Item
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0)
{
    return YES;
}
//移动Item时触发的方法
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0);
{
    
}


//添加
- (UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addBtn addTarget:self action:@selector(chuangAddBtnClick) forControlEvents:UIControlEventTouchUpInside];
        _addBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_addBtn setTitleColor:SELECTEDCOLOR forState:0];
        [_addBtn setTitle:@"添加" forState:UIControlStateNormal];
    }
    return _addBtn;
}

//删除
- (void)requestDeleteId:(NSString *)delId {
    [MBProgressHUD mj_showLoading];
    __weak typeof(self) weakSelf = self;
    [SYRequestAPI fd_requestFenZuSorDeleteId:delId isDelete:@"0" success:^(BOOL isSuccess) {
        [MBProgressHUD mj_hideHUD];
        [MBProgressHUD zr_showError:@"删除成功"];
        [NSObject executeRunloop:^{
            [weakSelf requestDataListArr];
        } afterDelay:1];
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUD];
        [MBProgressHUD zr_showError:error.message];
    }];
}

//合并文件夹
- (void)yidongwenjianjiaOldId:(NSString *)oldId newId:(NSString *)newId {
    [MBProgressHUD mj_showLoading];
    __weak typeof(self) weakSelf = self;
    
    [SYRequestAPI fd_requestFenZuSorQuestionBatchTransFerSortId:newId oldSortId:oldId success:^(BOOL isSuccess) {
        [MBProgressHUD mj_hideHUD];
        
        [MBProgressHUD zr_showError:@"合并成功"];
        [NSObject executeRunloop:^{
            [weakSelf requestDataListArr];
        } afterDelay:1];
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUD];
    }];
    
}


//添加
- (void)chuangAddBtnClick {
    _alerView = [[SYNewAlerView alloc] init];
    [_alerView showAler:_alerView titleName:@"添加分组" textFielPlo:@" 分组名称"];
    __weak typeof(self) weakSelf = self;
    _alerView.block = ^(NSString *titleName) {//先这样写着。到时候在更改
        [weakSelf reuqestdataName:titleName fzId:@"0"];
    };
}

- (void)reuqestdataName:(NSString *)name fzId:(NSString *)fzid {
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    NSString *message = nil;
    if ([fzid isEqualToString:@"0"]) {
        message = @"添加成功";
    } else {
        message = @"修改成功";
    }
    __weak typeof(self) weakSelf = self;
    [SYRequestAPI fd_requestFenZuSortAddId:fzid name:name remark:@"" success:^(BOOL isSuccess) {
        [MBProgressHUD mj_hideHUDForView:self.view];
        [MBProgressHUD zr_showError:message];
        [NSObject executeRunloop:^{
            [weakSelf requestDataListArr];
        } afterDelay:1];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
        [MBProgressHUD zr_showError:error.message];
    }];
    
}



- (void)requestDataListArr {
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    __weak typeof(self) weakSelf = self;
    [SYRequestAPI fd_requestFenZuQuestionSortKeyWord:@"" success:^(NSMutableArray *listArr) {
        [MBProgressHUD mj_hideHUDForView:self.view];
        weakSelf.dataListArr = listArr;
        [weakSelf.mainCollectionViewController reloadData];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
        
        
    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
